package itsm.isperp.module.utils;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.module.entity.app.AppUser;
import itsm.isperp.module.entity.wechat.WechatChat;
import itsm.isperp.module.service.app.AppUserService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpInMemoryConfigStorage;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpMessage;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2015-9-1
 * @since 1.0
 * 
 */
public class WechatChatUtils {

	public static final Logger logger = LoggerFactory.getLogger(WechatChatUtils.class);

	public static void sendCpMessage(String userid, String content) {
		try {
			WxCpInMemoryConfigStorage config = ContextHolder.getWxCpConfig();
			String[] userIds = userid.split(",");
			
			for (int i = 0; i < userIds.length; i++) {
			  if(config!=null && StringUtils.isNotBlank(userIds[i]))
			  {
			    WxCpMessage m = new WxCpMessage();
	        m.setAgentId(config.getAgentId());
	        m.setToUser(userIds[i]);
	        m.setMsgType("text");
	        m.setContent(content);
	        WxCpService wxCpService = ContextHolder.getSpringBean("wxCpService");
	        wxCpService.messageSend(m);
			  }
				
			}
		} catch (Exception e) {
			logger.error("--微信消息发送失--"+e.getMessage(), e);
		}
	}

	public static void chat(WechatChat message) throws WxErrorException {
		WxCpInMemoryConfigStorage config = ContextHolder.getWxCpConfig();
		if (config != null) {
			WxCpService wxCpService = ContextHolder.getSpringBean("wxCpService");
			AppUserService appUserService = ContextHolder.getSpringBean("appUserService");

			AppUser u = appUserService.findByOpenid(message.getOpenid(), "name");

			WxCpMessage m = new WxCpMessage();
			m.setAgentId(config.getAgentId());

			m.setToUser(u.getName());
			m.setMsgType("text");
			m.setContent(message.getSendContent());

			wxCpService.messageSend(m);
		}
	}

}
